<template>
	<view class="content">
		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view v-for="(item, index) in tabBars" :key="item.id" class="nav-item" :class="{ current: index === tabCurrentIndex }" :id="'tab' + index" @click="changeTab(index)">
				{{ item.name }}
			</view>
		</scroll-view>

		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh" @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<scroll-view class="panel-scroll-box" :scroll-y="enableScroll" @scrolltolower="loadMore">
						<!-- 工单列表 -->
						<view v-for="(item, index) in orderList" :key="index" @click="navToDetails(item)">
							<uni-group>
								<view class="uni-flex uni-row" style="flex-direction: row; justify-content: space-between;">
									<view>
										<view>
											<text style="margin-right:20px;">编号：{{ item.orderCode }}</text>
											<!-- <text>{{ '\u00a0\u00a0\u00a0' }}</text> -->
											<text>类型：{{ item.orderTypeShow }}</text>
										</view>
										<!-- 	<view>
											<text>描述：{{ item.orderDesc }}</text>
										</view> -->
										<view class="news-item" style="color:#6A6A6A">{{ item.orderDesc }}</view>
										<text class="time" style="color:#B0B0B0">{{item.createTime}}</text>
									</view>
									<view v-if="item.orderStatus === '2'">
										<view class="tagbutton"><uni-tag :circle="true" text="待抢单" type="warning" /></view>
									</view>
									<view v-else-if="item.orderStatus === '5'">
										<view class="tagbutton"><uni-tag :circle="true" text="进行中" type="primary" /></view>
									</view>
									<view v-else-if="item.orderStatus === '4' || item.orderStatus === '6'">
										<view class="tagbutton"><uni-tag :circle="true" text="已取消" type="error" /></view>
									</view>
									<view v-else-if="item.orderStatus === '7'">
										<view class="tagbutton"><uni-tag :circle="true" text="已完成" type="success" /></view>
									</view>
									<view v-else-if="item.orderStatus === '8'">
										<view class="tagbutton"><uni-tag :circle="true" text="已评价" type="success" /></view>
									</view>
									<view v-else>
										<view class="tagbutton"><uni-tag :circle="true" text="其他" type="info" /></view>
									</view>
								</view>
							</uni-group>
						</view>

						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
	</view>
</template>
<script>
import mixAdvert from '@/components/mix-advert/vue/mix-advert';
import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
import mixLoadMore from '@/components/mix-load-more/mix-load-more';
import { listUserOrder, listOptOrder, listAdminOrder } from '@/api/business/order';
import store from '@/store'

let windowWidth = 0,
	scrollTimer = false,
	tabBar;
let _self,
	timer = null;
export default {
	components: {
		mixPulldownRefresh,
		mixLoadMore,
		mixAdvert
	},
	data() {
		return {
			tabCurrentIndex: 0, //当前选项卡索引
			scrollLeft: 0, //顶部选项卡左滑距离
			enableScroll: true,
			tabBars: [],
			tabList: [
				{
					name: '全部工单',
					id: '1',
					// 总条数
					total: 0,
				},
				{
					name: '待抢单',
					id: '2',
					// 总条数
					total: 0,
				},
				{
					name: '进行中',
					id: '3',
					// 总条数
					total: 0,
				},
				{
					name: '已完成',
					id: '4',
					// 总条数
					total: 0,
				}
			],
			// 工单列表数据
			orderList: [],
			// 总条数
			total: 0,
			// 加载更多 0加载前，1加载中，2没有更多了
			loadMoreStatus : 0,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				orderStatus: ''
			},
		};
	},
	computed: {
	},
	created() {
		const roles = store.getters && store.getters.roles
		console.log('roles', roles)
	},
	async onLoad(option) {
		// console.log('onLoad', this.queryParams.pageNum)
		_self = this;
		// 获取屏幕宽度
		windowWidth = uni.getSystemInfoSync().windowWidth;
		this.tabCurrentIndex = option.tab - 1;
	},
	onReady() {},
	onShow() {
		console.log('onShow')
		this.loadTabbars();
	},
	methods: {
		/** 查询工单列表 */
		getOrderList(item, type, callback) {
			this.tabChangeReload();
			// 管理员权限
			if (this.checkRole(['admin'])) {
				console.log('admin')
				listAdminOrder(this.queryParams).then(res => {
					if(res.code === 200){
						if(type === "refresh" || this.orderList.length < res.total){
							this.orderList = [...this.orderList, ...res.rows];
							this.total = res.total;
						}
					}
					callback(item, type)
				});
				// 用户权限
			} else if (this.checkRole(['user'])) {
				console.log('user')
				listUserOrder(this.queryParams).then(res => {
					// console.log('response', response);
					if(res.code === 200){
						if(type === "refresh" || this.orderList.length < res.total){
							this.orderList = [...this.orderList, ...res.rows];
							this.total = res.total;
						}
					}
					callback(item, type)
				});
				// 运维权限
			} else if (this.checkRole(['opt'])) {
				console.log('opt')
				listOptOrder(this.queryParams).then(res => {
					if(res.code === 200){
						if(type === "refresh" || this.orderList.length < res.total){
							this.orderList = [...this.orderList, ...res.rows];
							this.total = res.total;
						}
					}
					callback(item, type)
				});
			}
		},
		//获取tab列表
		loadTabbars() {
			let tabList = this.tabList;
			tabList.forEach(item => {
				item.refreshing = 0;
			});
			this.tabBars = tabList;
			this.loadNewsList('refresh');
		},
		//工单列表
		loadNewsList(type) {
			// console.log('加载一次', type)
			let tabItem = this.tabBars[this.tabCurrentIndex];
			//type add 加载更多 refresh下拉刷新
			if (type === 'add') {
				if (this.loadMoreStatus === 2) {
					return;
				}
				this.loadMoreStatus = 1;
			}
			else if (type === 'refresh') {
				this.queryParams.pageNum = 1;
				this.orderList = []; //刷新前清空数组
				tabItem.refreshing = 1;
				this.loadMoreStatus = 1;
			}
			// console.log('this.orderList', this.orderList)
			// console.log('this.orderList.length', this.orderList.length)
			// console.log('this.total', this.total)
			if(this.orderList.length !== 0 && this.orderList.length < this.total){
				this.queryParams.pageNum++;
				// console.log('再次分页', this.queryParams.pageNum)
			}
			this.getOrderList(tabItem, type, this.loadListCallBack);
			// console.log('tabItem', tabItem)
			// console.log('当前请求页数', this.queryParams.pageNum)
		},
		// 处理状态回调函数
		loadListCallBack(tabItem, type){
			// console.log('this.total', this.total)
			// console.log('type', type)
			// console.log('refreshing', tabItem.refreshing)
			//下拉刷新 关闭刷新动画
			if (type === 'refresh') {
				this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
				// this.loadMoreStatus = 0;
			}
			tabItem.refreshing = 0;
			//上滑加载 处理状态
			this.loadMoreStatus = this.orderList.length === this.total ? 2 : 0;
			// console.log('this.loadMoreStatus', this.loadMoreStatus)
		},
		//工单详情
		navToDetails(item) {
			// console.log(item);
			uni.navigateTo({
				url: '/pages/work/detail/index?id=' + item.id
			});
		},
		//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
		setEnableScroll(enable) {
			if (this.enableScroll !== enable) {
				this.enableScroll = enable;
			}
		},
		//tab切换
		async changeTab(e) {
			// console.log("tab切换", e)
			this.queryParams.pageNum = 1;
			// console.log('scrollTimer', scrollTimer);
			if (scrollTimer) {
				//多次切换只执行最后一次
				clearTimeout(scrollTimer);
				scrollTimer = false;
			}
			let index = e;
			//e=number为点击切换，e=object为swiper滑动切换
			if (typeof e === 'object') {
				index = e.detail.current;
				// console.log('index', index)
			}
			if (typeof tabBar !== 'object') {
				tabBar = await this.getElSize('nav-bar');
			}
			//计算宽度相关
			let tabBarScrollLeft = tabBar.scrollLeft;
			let width = 0;
			let nowWidth = 0;
			//获取可滑动总宽度
			for (let i = 0; i <= index; i++) {
				let result = await this.getElSize('tab' + i);
				width += result.width;
				if (i === index) {
					nowWidth = result.width;
				}
			}
			if (typeof e === 'number') {
				//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
				this.tabCurrentIndex = index;
			}
			//延迟300ms,等待swiper动画结束再修改tabbar
			scrollTimer = setTimeout(() => {
				if (width - nowWidth / 2 > windowWidth / 2) {
					//如果当前项越过中心点，将其放在屏幕中心
					this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
				} else {
					this.scrollLeft = 0;
				}
				if (typeof e === 'object') {
					this.tabCurrentIndex = index;
				}
				this.tabCurrentIndex = index;
				this.loadNewsList('refresh');
			}, 300);
		},
		// 切换tab时修改工单状态重新获取数据
		tabChangeReload() {
			if (this.tabCurrentIndex === 1) {
				this.queryParams.orderStatus = '2';
			} else if (this.tabCurrentIndex === 2) {
				this.queryParams.orderStatus = '5';
			} else if (this.tabCurrentIndex === 3) {
				this.queryParams.orderStatus = '7';
			} else {
				this.queryParams.orderStatus = '';
			}
		},
		//获得元素的size
		getElSize(id) {
			return new Promise((res, rej) => {
				let el = uni.createSelectorQuery().select('#' + id);
				el.fields(
					{
						size: true,
						scrollOffset: true,
						rect: true
					},
					data => {
						res(data);
					}
				).exec();
			});
		},
		//上滑加载
		loadMore() {
			// console.log('loadMore')
			this.loadNewsList('add');
		},
		//下拉刷新
		onPulldownReresh() {
			this.loadNewsList('refresh');
		}
	}
};
</script>
<style lang="scss">
page,
.content {
	background-color: #f8f8f8;
	height: 100%;
	overflow: hidden;
}

/* 顶部tabbar */
.nav-bar {
	position: relative;
	z-index: 10;
	height: 90rpx;
	white-space: nowrap;
	box-shadow: 0 2upx 8upx rgba(0, 0, 0, 0.06);
	background-color: #fff;

	.nav-item {
		display: inline-block;
		width: 180rpx;
		height: 90rpx;
		text-align: center;
		line-height: 90rpx;
		font-size: 30rpx;
		color: #303133;
		position: relative;

		&:after {
			content: '';
			width: 0;
			height: 0;
			border-bottom: 4upx solid #007aff;
			position: absolute;
			left: 50%;
			bottom: 0;
			transform: translateX(-50%);
			transition: 0.3s;
		}
	}

	.current {
		color: #007aff;

		&:after {
			width: 50%;
		}
	}
}

.swiper-box {
	height: 100%;
}

.panel-scroll-box {
	height: 100%;

	.panel-item {
		background: #fff;
		padding: 30px 0;
		border-bottom: 2px solid #000;
	}
}

/**
 * 新闻列表 直接拿的nvue样式修改，,
 * 一共需要修改不到10行代码, 另外px需要直接修改为upx，只有单位不一样，计算都是一样的
 * 吐槽：难道不能在编译的时候把nuve中的upx转为px? 这样就不用修改单位了
 */
.news-item {
	position: relative;
}
.news-item {
	width: 75%;
	padding: 5px 0;
}
.tagbutton {
	position: absolute;
	top: 20px;
	right: 10px;
}
.uni-flex {
	position: relative;
	display: flex;
	flex-direction: row;
}

.uni-column {
	flex-direction: column;
}
</style>
